<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\Transfer;
use app\models\user\UserAccount;

class TransferController extends H5Controller
{
    // 余额转让
    public function actionExecute()
    {

        $transaction = \Yii::$app->db->beginTransaction();

        try {
            $send_id = $this->user->id;
            $received_id = $this->post('received_id');

            if ($send_id == $received_id) {
                return $this->fail('错误');
            }

            $amount = intval($this->post('amount'));
            if ($amount <= 0.01) {
                return $this->fail('金额错误');
            }
            $send = UserAccount::findOne(['user_id' => $send_id]);
            $received = UserAccount::findOne(['user_id' => $received_id]);
            if (!$send || !$received) {
                return $this->fail('操作错误,请检查用户id');
            }
            if ($send->balance < $amount) {
                return $this->fail('余额不足');
            }
            $send->balance -= $amount;
            $send->save();
            $received->balance += $amount;
            $received->save();// 日志
            $log = new Transfer();
            $log->send_id = $send_id;
            $log->received_id = $received_id;
            $log->amount = $amount;
            $log->save();

            // var_dump($log->getFirstErrors());exit;

            $transaction->commit();

            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
    }
}